<!-- 字典数据 -->
<template>
  <div class="app-container drawer-container">
    <div class="block">
      <el-form
        ref="dataFormRef"
        :model="form"
        :inline="true"
        size="default"
        label-width="100"
        label-position="left"
        :rules="rules"
        class="mt-[15px]"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡检计划名称" prop="planSetName">
              <el-input
                v-model="form.planSetName"
                placeholder="请输入"
                clearable
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planSetType">
              <el-radio-group
                v-model="form.planSetType"
                @change="f_ChangePlanType"
              >
                <el-radio :value="1">日计划</el-radio>
                <el-radio :value="2">周计划</el-radio>
                <el-radio :value="3">月计划</el-radio>
                <el-radio :value="4">季计划</el-radio>
                <el-radio :value="5">年计划</el-radio>
                <el-radio :value="0">自定义</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检任务" prop="taskSetId">
              <el-select
                placeholder="请选择"
                size="default"
                v-model="form.taskSetId"
                @change="f_ChangeTask"
              >
                <el-option
                  :label="item.taskSetName"
                  :value="item.taskSetId"
                  :key="item.taskSetId"
                  v-for="item in taskData"
                  :disabled="!item.isEnabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.planSetType != 1"
              label="选择时间"
              prop="isAvoidHoliday"
            >
              <el-date-picker
                v-if="
                  form.planSetType == 3 ||
                  form.planSetType == 4 ||
                  form.planSetType == 5
                "
                v-model="form.planDate"
                type="date"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                append-to-body="false"
                :disabled-date="disabledEffectiveRangeDate"
                :clearable="false"
                format="YYYY-MM-DD"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD"
              />
              <el-select
                v-if="form.planSetType == 2"
                placeholder="请选择时间"
                multiple
                size="default"
                v-model="form.planDate"
              >
                <el-option label="周一" value="1" />
                <el-option label="周二" value="2" />
                <el-option label="周三" value="3" />
                <el-option label="周四" value="4" />
                <el-option label="周五" value="5" />
                <el-option label="周六" value="6" />
                <el-option label="周日" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="避开节假日" prop="isAvoidHoliday">
              <el-radio-group v-model="form.isAvoidHoliday">
                <el-radio :value="true">避开</el-radio>
                <el-radio :value="false">不避开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检时间范围" prop="name4">
              <b style="color: red; position: absolute; top: 0; left: -108px"
                >*</b
              >
              <el-time-picker
                v-if="form.planSetType != '0'"
                v-model="datetimeRange"
                is-range
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
              />

              <el-date-picker
                v-else
                v-model="datetimeRange"
                is-range
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                type="daterange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检类型">
              <el-input
                :value="currentTaskData.taskSetType == 2 ? '区域' : '线路'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检线路">
              <el-input v-model="currentTaskData.inspDestName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检部门">
              <el-input
                v-model="currentTaskData.inspDeppartmentName"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检人员">
              <el-input v-model="currentTaskData.inspUserName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="footer pb-[15px] mt-[-20px] pr-[15px]">
      <el-button type="primary" @click="debounce_fun(false)">保存</el-button>
      <el-button type="primary" @click="debounce_fun(true)"
        >保存并立即生成</el-button
      >
      <el-button @click="f_CloseDialog">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DictData",
  inheritAttrs: false,
});
import { debounce } from "lodash";
import moment from "moment";
import PlanAPI from "@/api/PlanAPI";
import { find, cloneDeep } from "lodash";
const emits = defineEmits(["close"]);
const props = defineProps({
  taskData: {
    type: Array,
    default: () => {
      return [];
    },
  },
  form: {
    type: Array,
    default: () => {
      return {};
    },
  },
});
const datetimeRange = ref([new Date(), new Date()]);
const taskData = props.taskData;
const form = reactive(props.form);
const formRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const loading = ref(false);
const currentTaskData = ref({});

const rules = reactive({
  planSetName: [{ required: true, message: "请输入", trigger: "blur" }],
  planSetType: [{ required: true, message: "请输入", trigger: "blur" }],
  inspDestId: [{ required: true, message: "请输入", trigger: "blur" }],
  taskSetId: [{ required: true, message: "请输入", trigger: "change" }],
});

// 放抖
const debounce_fun = debounce(f_HandleSubmit, 1000);

// change
function f_ChangePlanType() {
  if (form.planSetType == 3 || form.planSetType == 4 || form.planSetType == 5) {
    form.planDate = "";
  } else if (form.planSetType == 2) {
    form.planDate = [];
  } else {
    form.planDate = "";
  }
}

function f_DisabledDate(time) {
  // 获取当前日期
  const today = new Date();
  // 将时、分、秒、毫秒归零，只留下年月日
  today.setHours(0, 0, 0, 0);
  // 获取当前时间
  const currentTime = new Date();
  // 设置晚上十点的时间
  const tenPM = new Date();
  tenPM.setHours(23, 0, 0, 0);
  // 如果当前时间晚于晚上十点，则禁用
  if (currentTime.getTime() >= tenPM.getTime()) {
    return true;
  }
  // 将传入的日期 time 也归零
  // time.setHours(0, 0, 0, 0);
  // 如果传入的日期和当天日期不一致，则禁用
  return time.getTime() !== today.getTime();
}

function f_GetWeekDataList() {
  //根据日期获取本周周一~周日的年-月-日
  var weekList = [];
  var date = new Date();
  //判断本日期是否为周日，获取本周一日期
  if (String(date.getDay()) == "0") {
    date.setDate(date.getDate() - 6);
  } else {
    date.setDate(date.getDate() - date.getDay() + 1);
  }
  var myDate = String(date.getDate());
  var myMonth = String(date.getMonth() + 1);
  if (date.getDate() < 10) {
    myDate = "0" + myDate;
  }
  if (date.getMonth() + 1 < 10) {
    myMonth = "0" + myMonth;
  }
  weekList.push(date.getFullYear() + "-" + myMonth + "-" + myDate);
  // 获取周二以后日期
  for (var i = 0; i < 6; i++) {
    date.setDate(date.getDate() + 1);
    myDate = Number(date.getDate());
    myMonth = Number(date.getMonth() + 1);
    if (date.getDate() < 10) {
      myDate = "0" + myDate;
    }
    if (date.getMonth() + 1 < 10) {
      myMonth = "0" + myMonth;
    }
    weekList.push(date.getFullYear() + "-" + myMonth + "-" + myDate);
  }
  let checkDay = [];
  form.planDate.forEach((item) => {
    checkDay.push(weekList[Number(item) - 1]);
  });
  return checkDay;
}

// 提交数据
function f_HandleSubmit(flag) {
  console.log(flag);
  if (!datetimeRange.value || datetimeRange.value.length == 0) {
    ElMessage.error("请填写巡检时间范围！");
    return;
  }
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      form.planStartTime = moment(datetimeRange.value[0]).format(
        "yyyy-MM-DD HH:mm"
      );
      form.planEndTime = moment(datetimeRange.value[1]).format(
        "yyyy-MM-DD HH:mm"
      );
      let data = cloneDeep(form);
      if (flag) {
        data.generateTask = true;
        data.status = 1;
      } else {
        data.generateTask = false;
        data.status = 2;
      }
      data.taskSetCycle = {
        planDate: data.planDate,
      };
      if (data.planSetType == 2) {
        data.planDate = f_GetWeekDataList();
      } else if (data.planSetType == 1 || data.planSetType == 0) {
        data.planDate = [new Date()];
      } else {
        data.planDate = [data.planDate];
      }
      PlanAPI.api_add(data).then(({ data, succeeded }) => {
        if (succeeded) {
          ElMessage.success("操作成功！");
          f_CloseDialog();
        }
      });
    }
  });
}

// 关闭弹窗
function f_CloseDialog() {
  emits("close");
}

// 任务 change
function f_ChangeTask() {
  let data = find(taskData, { taskSetId: form.taskSetId });
  if (data) {
    currentTaskData.value = data;
    console.log(data);
  }
}

onMounted(() => {
  if (form.planSetId) {
    f_ChangeTask();
    if (form.planSetType == 2) {
      let arr = [];
      form.taskSetCycle.planDate.forEach((item) => {
        arr.push(item);
      });
      form.planDate = arr;
    } else {
      form.planDate = form.taskSetCycle.planDate;
    }

    console.log(form);
    datetimeRange.value = [form.planStartTime, form.planEndTime];
  }
});
</script>
<style lang="scss" scoped>
.drawer-container {
  background: transparent;

  .block {
    padding: 15px;
    margin-bottom: 20px;
    background: #fff;

    .title {
      padding-bottom: 10px;
      margin-bottom: 20px;
      font-size: 14px;
      font-weight: bold;
      border-bottom: 1px dashed #eee;
    }

    :deep .el-form {
      .el-form-item {
        width: 100%;

        .el-form-item__label {
          font-size: 12px !important;
        }
      }
    }
  }
}

.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15px;
  text-align: center;
  background: #fff;
  border-top: 1px dashed #eee;

  button {
    width: 160px !important;
    height: 28px !important;
    margin-right: 40px;
    margin-left: 40px;
    border-radius: 15px;

    > span > svg {
      margin-right: 6px;
    }
  }
}
</style>
